<template>
  <div>
    <a-row justify="space-between" align="middle">
      <a-col>
        <RouteTitle isBack />
      </a-col>
      <a-col>
        <span style="margin-right: 10px;">更新下载数据，请手动刷新</span>
        <a-tooltip placement="topRight">
          <template #title>刷新列表</template>
            <a-button type="primary" @click="refreshClick" :spin="loading" style="border-radius: 4px;" >
    <template #icon>
     <redo-outlined  />
    </template>
    刷新
  </a-button>
         
        </a-tooltip>
      </a-col>
    </a-row>
    <a-table style="margin-top: 10px" :dataSource="dataSource" :columns="columns" :pagination="pagination"
      @change="handleTableChange" :loading="loading">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'name'">
          <a-row :gutter="[16, 16]" align="middle">
            <a-col>
              <cu-icon v-if="record.file_type == 'zip'" class="icon play-icon" type="icon-zip"
                style="font-size: 40px" />
              <cu-icon v-if="record.file_type == 'xls'" class="icon play-icon" type="icon-icon_xlsx"
                style="font-size: 40px" />
              <cu-icon v-if="record.file_type == ''" class="icon play-icon" type="icon-yasuobao-icon"
                style="font-size: 40px" />
            </a-col>
            <a-col>
              <div>{{ record.name }}</div>
              <div style="color: #999">{{ record.size_text }}</div>
            </a-col>
          </a-row>
        </template>
        <template v-if="column.key === 'status_text'">
          <div v-if='!record.isdown_ing'>
            {{ record.status_text }}
          </div>
          <div v-else>
            <div class="S_down_ing">下载中</div>
            <a-progress :percent="record.progress" :showInfo="true" type="line" size="small" :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }" status="active" />
          </div>
        </template>
        <template v-if="column.key === 'remain_days'">
          <span v-if="record.remain_days"> {{ record.remain_days }}天 </span>
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-button v-if="record.open_down == 0" type="text" style="color: var(--ss-primary-color)" :loading="record.btn_loading"
            @click="debounceddownloadClick(record, index)" :disabled="record.status !== 1">下载</a-button>

          <a-button v-if="record.open_down == 1" type="text" style="color: var(--ss-primary-color)" 
            @click="debounceddownloadClicks(record, index)" >下载</a-button>

          <a-button type="text"  @click="debouncedDel(record)"
             >删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, createVNode } from "vue";
import request from "../../../common/utils/request";
import { message, Modal } from "ant-design-vue";
import { RedoOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { saveAs } from "file-saver";
import { debounce } from "lodash";
import utils from "../../../common/utils/utils";

export default defineComponent({
  name: "Download",
  components: { RedoOutlined, ExclamationCircleOutlined },
  setup() {
    const state = reactive({
      count: 0,
      dataSource: [],
      columns: [
        {
          title: "名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "状态",
          dataIndex: "status_text",
          key: "status_text",
          width: 300,
        },
        {
          title: "时间",
          dataIndex: "created_at",
          key: "created_at",
        },
        {
          title: "剩余有效期",
          dataIndex: "remain_days",
          key: "remain_days",
        },
        {
          title: "操作",
          dataIndex: "action",
          key: "action",
          width: 300,
        },
      ],
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      progress: 0
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getDownloadList();
    };

    const getDownloadList = () => {
      let params = {
        page: state.page,
        pageSize: state.pageSize,
      };
      state.loading = true;
      request
        .get("/work_ai", "/user/shotstack/download/list", params)
        .then((res) => {
          state.dataSource = res.result.data.map((item) => {
            return {
              ...item,
              isdown_ing: false,
              dataSource: 0,
              btn_loading: false
            };
          });
          state.total = res.result.total;
          state.loading = false;
        })
        .catch(() => {
          state.loading = false;
        });
    };
    getDownloadList();

    // 下载按钮 防抖
    const debounceddownloadClick = debounce((data, index) => downloadClick(data, index), 1000,
    {
      leading: true,
      trailing: false 
      });

          // 下载按钮 防抖
    const debounceddownloadClicks = debounce((data, index) => downloadClicks(data, index), 1000,
    {
      leading: true,
      trailing: false 
      });

    // 下载按钮 防抖
    const debouncedDel = debounce((data) => delFn(data), 1000,
    {
      leading: true,
      trailing: false 
      });

    const delFn = (data) => {
       Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "删除操作无法恢复，您确定要删除下载包吗？",
    cancelText: "取消",
    okText: "确定",
    onOk() {
      request
        .del("/work_ai", "/user/shotstack/download/delete", {id: data.id})
        .then((res) => {
          message.success("删除成功!")
      getDownloadList();

        })
    },
    onCancel() {},
  });
      }

    const downloadClicks = (data, index) => {
      if (data.file_url) {
        window.open(data.file_url)    
      }
      }

    // 分片下载函数
    const downloadClick = async (data, index) => {
      state.dataSource[index].isdown_ing = true;
      state.dataSource[index].btn_loading = true

      try {
        const { size: fileSize } = data;
        const chunkSize = 1024 * 500; // 每个分片的大小，这里设置为1MB
        const chunks = Math.ceil(fileSize / chunkSize); // 计算需要下载的分片数量

        let downloadedChunks = 0;
        const fileContent = [];
        let currentHide;
        const base_url = `/work_ai/user/shotstack/download?id=${data.id}`;

        const params = getParams(); // 获取参数对象

        for (let i = 0; i < chunks; i++) {
          const start = i * chunkSize;
          const end = Math.min(start + chunkSize - 1, fileSize - 1);

          const options = {
            headers: { Range: `bytes=${start}-${end}` },
            responseType: "blob"
          };

          const res = await request.newDownload(base_url, { ...params }, options.headers, options.responseType);

          const blob = res.data;
          if (!(blob instanceof Blob)) {
            throw new Error('Unexpected data type received from server.');
          }

          fileContent.push(blob);
          downloadedChunks++;

          state.dataSource[index].progress = ((downloadedChunks / chunks) * 100).toFixed(0)
        }

        let blobType = data.blobType;
        if (! blobType) {
          blobType = 'application/zip';
        }
        const finalBlob = new Blob(fileContent, { type: blobType });

        // 验证最终 Blob 的大小是否与原始文件大小一致
        if (finalBlob.size !== fileSize) {
          throw new Error('Final blob size does not match the original file size.');
        }

        await downloadFile(finalBlob, data.name);

        message.success("下载成功");
        state.dataSource[index].isdown_ing = false;
        state.dataSource[index].btn_loading = false
        state.dataSource[index].progress = 0
      } catch (err) {
        message.error("下载失败");
        state.dataSource[index].isdown_ing = false;
        state.dataSource[index].btn_loading = false
        state.dataSource[index].progress = 0
      }
    };

    const getParams = () => ({
      org_id: utils.getOrgId(),
      user_token: utils.getUserToken(),
      cur_env: utils.isMobile() ? "h5" : import.meta.env.ELECTRON ? "desktop" : "pc",
      team_id: utils.getCurrentTeam()
    });

    const downloadFile = (blob, filename) => {
      const urlBlob = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = urlBlob;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(urlBlob);
    };



    // const downloadClick = async (data, index) => {
    //   state.dataSource[index].isdown_ing = true;

    //   try {
    //     const fileSize = data.size;
    //     const chunkSize = 1024 * 1024; // 每个分片的大小，这里设置为1MB
    //     const chunks = Math.ceil(fileSize / chunkSize); // 计算需要下载的分片数量

    //     let downloadedChunks = 0;
    //     const fileContent = [];

    //     let currentHide;

    //     const url = `/api/work_ai/user/shotstack/download?id=${data.id}`;

    //     for (let i = 0; i < chunks; i++) {
    //       const start = i * chunkSize;
    //       const end = Math.min(start + chunkSize - 1, fileSize - 1);

    //       try {
    //         const response = await fetch(url, {
    //           headers: { Range: `bytes=${start}-${end}` }
    //         });

    //         if (!response.ok) {
    //           throw new Error('Network response was not ok');
    //         }

    //         const blob = await response.blob();

    //         console.log(blob, '分片的blob内容99999999');

    //         // 确保 response.data 是 Blob 类型
    //         if (!(blob instanceof Blob)) {
    //           throw new Error('Unexpected data type received from server.');
    //         }

    //         fileContent.push(blob);
    //         downloadedChunks++;

    //         const progress = (downloadedChunks / chunks) * 100;
    //         if (currentHide) {
    //           message.destroy(currentHide);
    //         }
    //         currentHide = message.loading(`下载中... ${progress.toFixed(0)}%`, 0);
    //       } catch (err) {
    //         console.error(`Error downloading chunk ${i}: `, err);
    //         throw err;
    //       }
    //     }

    //     // 下载完成
    //     message.destroy(currentHide);

    //     const finalBlob = new Blob(fileContent, { type: 'application/zip' });
    //     // const finalBlob = new Blob(fileContent, { type: 'application/zip' });
    //     // const finalBlob = new Blob(fileContent, { type: 'application/octet-stream' });


    //     console.log(finalBlob, '最终合成的总得blob');
    //     const urlBlob = window.URL.createObjectURL(finalBlob);
    //     const link = document.createElement('a');
    //     link.href = urlBlob;
    //     link.setAttribute('download', data.name); // 这里需要从响应中获取正确的文件名
    //     document.body.appendChild(link);
    //     link.click();
    //     document.body.removeChild(link);

    //     window.URL.revokeObjectURL(urlBlob);

    //     message.success("下载成功");
    //     state.dataSource[index].isdown_ing = false;
    //   } catch (err) {
    //     message.error("下载失败");
    //   }
    // };




    // 下载功能
    // const downloadClick = async (data, index) => {
    //   state.dataSource[index].isdown_ing = true
    //   const hide = message.loading("下载中...", 0);
    //   try {
    //     const res = await request.downLoad("/work_ai", "/user/shotstack/download", { id: data.id });
    //     setTimeout(hide, 0);
    //     await new Promise((resolve) => {
    //       saveAs(res.data, res.fileName);
    //       resolve();
    //     });
    //     message.success("下载成功");
    //     state.dataSource[index].isdown_ing = false
    //   } catch (err) {
    //     message.error("下载失败");
    //   }
    // };


    const refreshClick = () => {
      getDownloadList();
    };

    return {
      ...toRefs(state),
      pagination,
      handleTableChange,
      downloadClick,
      refreshClick,
      debounceddownloadClick,
      debounceddownloadClicks,
      downloadClicks,
      debouncedDel,
      delFn
    };
  },
});
</script>

<style lang="less" scoped>
.redo-outlined {
  font-size: 20px;
  cursor: pointer;
  color: var(--ss-primary-color);
  padding-right: 20px;
}

.S_down_ing {
  display: flex;
  justify-content: center;
}
</style>
